<template>
  <view>
    <view>
      <img class="icon" src="~@/static/images/icon_weixin.png" @tap="weixinLogin">
    </view>
    <view>
      <!-- #ifdef H5 -->
      <cl-dialog title="扫码登录" :visible.sync="showWxQR">
        <text>扫码登录暂未启用</text>
      </cl-dialog>
      <!-- #endif -->
      <cl-dialog class="bind-mobile-ask-dlg" :visible="askBindMobile" title="绑定手机号">
        <text>未设置手机号，请绑定手机号</text>
        <button type="primary" open-type="getPhoneNumber" class="bind-mobile-ask-btn" round @getphonenumber="handleWxMobileLogin">绑定手机号</button>
      </cl-dialog>
    </view>
  </view>
</template>

<script>
import login from '@/api/login'

export default {
  name: 'MpWeixinLoginBtn',
  data() {
    return {
      showWxQR: false,
      askBindMobile: false
    }
  },
  methods: {
    weixinLogin() {
      // #ifdef MP-WEIXIN
      uni.getUserProfile({
        desc: '登录用户后台',
        success: res => {
          this.userInfo = res
          this.handleWxLogin()
        },
        fail: res => {
          uni.showToast({ icon: 'none', title: '您拒绝了授权' })
        }
      })
      // #endif
      // #ifdef H5
      this.showWxQR = true
      // #endif
    },

    handleWxLogin() {
      login
        .wxLogin({
          openid: uni.getStorageSync('openid'),
          iv: this.userInfo.iv,
          rawData: this.userInfo.rawData,
          signature: this.userInfo.signature,
          encryptedData: this.userInfo.encryptedData
        })
        .then(res => {
          // 如果没有返回token，就触发绑定手机号码
          if (res.missingMobile) {
            this.askBindMobile = true
            return
          }
          this.loginSuccess(res.token)
        })
        .catch(e => {
          uni.showModal({ title: '请重试' })
        })
    },
    handleWxMobileLogin(e) {
      const data = e.detail

      login
        .wxMobileLogin({
          openid: uni.getStorageSync('openid'),
          iv: data.iv,
          encryptedData: data.encryptedData,
          userInfo: {
            rawData: this.userInfo.rawData,
            signature: this.userInfo.signature,
            encryptedData: this.userInfo.encryptedData,
            iv: this.userInfo.iv
          }
        })
        .then(res => {
          this.loginSuccess(res.token)
        })
    },
    loginSuccess(token) {
      uni.setStorageSync('access_token', token)
      this.showWxQR = false
      this.askBindMobile = false
      this.$emit('finish')
    }
  }
}
</script>

<style scoped>
.bind-mobile-ask-btn {
  margin-top: 15px;
}
</style>
